package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.CustomizeException;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.utils.ImportUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("ordersetting")
public class OrderSettingController {

    @DubboReference
    private OrderSettingService orderSettingService;


    //  老式上传方法
    //  @PostMapping("upload")
    public Result fileUpload(@RequestParam("excelFile") MultipartFile multipartFile) {
        String filename = multipartFile.getOriginalFilename();
        log.info("[预约设置-upload-前端传入文件] - 文件名称: {} - 文件大小: {}", filename, multipartFile.getSize());
        if (filename.isEmpty()) {
            return new Result(false, "缺少文件名");
        }
        Workbook workbook = null;
        try {
            InputStream is = multipartFile.getInputStream();

            if (filename.endsWith("xls")) {
                workbook = new HSSFWorkbook(is);
            } else if (filename.endsWith("xlsx")) {
                workbook = new XSSFWorkbook(is);
            } else {
                return new Result(false, "文件格式不正确，请重新检查");
            }
            ArrayList<OrderSetting> orderSettingArrayList = new ArrayList<>();
            Sheet sheet = workbook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            for (int i = 1; i <= lastRowNum; i++) {
                Row row = sheet.getRow(i);
                OrderSetting orderSetting = parseRow(row);
                orderSettingArrayList.add(orderSetting);
            }
            log.info("[预约设置-upload] - orderSettingArrayList: {}", orderSettingArrayList);
            orderSettingService.uploadExcelFile(orderSettingArrayList);

        } catch (Exception e) {
            log.error("error: {}", e.getMessage());
            return new Result(false, "文件上传失败");
        }
        return new Result(true, MessageConst.IMPORT_ORDERSETTING_SUCCESS);
    }


    //老式解析方法
    public OrderSetting parseRow(Row row) {
        /*
         * @Date: 8:42 下午 2021/1/8
         * @param: [row]
         * @return: com.itheima.health.pojo.OrderSetting
         * @Description: 解析文件行内容
         */
        Date date = null;
        Integer number = null;
        //先判断第一行是不是空
        if (row.getCell(0) != null) {
            date = row.getCell(0).getDateCellValue();
        }
        if (row.getCell(1) != null) {//判断第二行是不是空
            double cellValue = row.getCell(1).getNumericCellValue();
            //强制把double转换成integer
            number = Double.valueOf(cellValue).intValue();
        }
        if (date == null || number == null) {
            throw new CustomizeException(String.format("缺少必填数据，%s第%d行", row.getSheet().getSheetName(), row.getRowNum() + 1));
        }
        log.info("[预约设置-upload] - data: {} - number: {}", date, number);
        return new OrderSetting(date, number);
    }


    @PreAuthorize("hasAuthority('ORDERSETTING')")
    //使用工具类新式上传方法
    @PostMapping("upload")
    public Result upload(@RequestParam("excelFile") MultipartFile file) {
        /*
         * @Date: 8:59 下午 2021/1/9
         * @param: [file]
         * @return: com.itheima.health.entity.Result
         * @Description: 获取rows，传给解析方法parseRows，解析数据得到List<orderSetting>
         */

        String filename = file.getOriginalFilename();
        List<List<Object>> lists = null;
        try {
            if (filename.endsWith(".xls")) {
                lists = ImportUtil.read2003Excel(file.getInputStream());
            } else if (filename.endsWith(".xlsx")) {
                lists = ImportUtil.read2007Excel(file.getInputStream());
            } else {
                throw new CustomizeException("文件格式上传错误，请重新上传");
            }
            ArrayList<OrderSetting> orderSettingArrayList = parseRows(lists);
            log.info("[预约设置-upload] - 解析后数据List<OrderSetting>: {}", orderSettingArrayList);

            orderSettingService.add(orderSettingArrayList);
            return new Result(true, MessageConst.IMPORT_ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.IMPORT_ORDERSETTING_FAIL);
        }

    }


    //新式解析方法
    public ArrayList<OrderSetting> parseRows(List<List<Object>> lists) throws ParseException {
        /*
         * @Date: 8:46 下午 2021/1/9
         * @param: [lists]
         * @return: java.util.ArrayList<com.itheima.health.pojo.OrderSetting>
         * @Description: 解析文件
         */
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        ArrayList<OrderSetting> orderSettingArrayList = new ArrayList<>();

        for (int i = 1; i <= lists.size(); i++) {
            //获取每一行
            List<Object> list = lists.get(i);
            OrderSetting orderSetting = new OrderSetting();
            //获取每一行第一个单元格数据
            Date date = sdf.parse(String.valueOf(list.get(0)));
            orderSetting.setOrderDate(date);
            //获取每一行第一个单元格
            orderSetting.setNumber(Integer.valueOf(String.valueOf(list.get(1))));
            orderSettingArrayList.add(orderSetting);
        }

        return orderSettingArrayList;

    }

    @PreAuthorize("hasAuthority('ORDERSETTING')")
    @GetMapping("getOrderSettingByMonth")
    public Result getOrderSettingByMonth(Integer year, Integer month) {
        /*
         * @Date: 5:12 下午 2021/1/9
         * @param: [year, month]
         * @return: com.itheima.health.entity.Result
         * @Description: 根据前端传入年月来获取预约人数
         */
        log.info("[预约-预约设置-getOrderSettingByMonth-前端传入数据] - year: {} - month: {}", year, month);
        List<Map<String, Object>> orderSettingList = orderSettingService.getOrderSettingByMonth(year, month);
        log.info("[预约-预约设置-getOrderSettingByMonth-后端返回数据] - orderSettingList: {}", orderSettingList);

        if (orderSettingList == null) {
            return new Result(false, MessageConst.GET_ORDERSETTING_FAIL);
        }
        return new Result(true, MessageConst.GET_ORDERSETTING_SUCCESS, orderSettingList);
    }


    @PreAuthorize("hasAuthority('ORDERSETTING')")
    @PostMapping("editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting) {
        log.info("[预约-预约设置-editNumberByDate-前端传入数据] - orderSetting: {}", orderSetting);

        orderSettingService.editNumberByDate(orderSetting);
        return new Result(true, MessageConst.ORDERSETTING_SUCCESS);
    }


}
